package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.AppThreadLocalUtil;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.Charset;
import java.util.HashMap;

@Service
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 登录
     * 真实的登录
     * 游客登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotEmpty(dto.getPassword())){
            //通过用户名和密码进行真实的登录
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(null == apUser){
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "用户名或密码错误");
            }

            //不为空则获取他的盐 然后用明文的密码再次加密 然后比较2个密文
            String salt = apUser.getSalt();
            String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(Charset.forName("utf-8")));
            if(!pwd.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名或密码错误");
            }

            //登录成功-构建返回的结果
            HashMap<String, Object> data = new HashMap<>();
            apUser.setSalt("");
            apUser.setPassword("");
            data.put("user", apUser);
            data.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));

            return ResponseResult.okResult(data);
        }else{
            //游客登录
            HashMap<String, Object> data = new HashMap<>();
            data.put("token", 0L);
            return ResponseResult.okResult(data);
        }
    }
}
